import React, { useRef, useEffect } from 'react';
import _get from 'lodash/get';
import useIframeMessage from '@/components/useIframeMessage';
import styles from './IframeWrapper.less';

const resizeIframe = (obj, contentHeight, maxHeight, setHeight) => {
  if (obj.contentWindow) {
    let height = contentHeight;
    if (setHeight) {
      obj.style.height = setHeight(height);
      return;
    }
    if (maxHeight) {
      height = Math.min(maxHeight, height);
    }
    obj.style.height = `${height}px`;
  }
}

const IframeWrapper = ({ src, maxHeight, setHeight, autoFitHeight = false, style, messageHandlers = [], getContentWindow, getFrameRef, iframeStyle = {} }) => {

  const iframeRef = useRef(null);

  useIframeMessage([ 
    (msg) => {
      if (autoFitHeight && msg.type === 'height') {
        resizeIframe(iframeRef.current, Number(msg.data), maxHeight, setHeight);
      }
    },
    ...messageHandlers,
  ]);

  useEffect(() => {
    if (getFrameRef) {
      getFrameRef(iframeRef);
      return () => {
        getFrameRef(undefined);
      }
    }
    if (getContentWindow) {
      const temp = () => _get(iframeRef.current, 'contentWindow', null);
      getContentWindow(temp);
    }
  },[]);

  return (
    <div className={styles.root} style={style || {}}>
      <iframe
        allowFullScreen
        frameBorder={0}
        src={src}
        title="Exploerer"
        ref={iframeRef}
        style={iframeStyle}
      />
    </div>
  );
}

export default IframeWrapper;

